package net.ib.mtalk.ui.buddy.talk;

import java.io.File;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;

import com.google.protobuf.micro.InvalidProtocolBufferMicroException;

import net.ib.mntalk.protocol.Common.BuddyInfo;
import net.ib.mntalk.protocol.Common.Calendar;
import net.ib.mntalk.protocol.Common.UUIDMsg;
import net.ib.mtalk.R;
import net.ib.mtalk.constant.MTalkConstant;
import net.ib.mtalk.database.DatabaseContract.BuddyTable;
import net.ib.mtalk.ui.buddy.item.BuddyUUIDItem;
import net.ib.mtalk.ui.favorite.FavoriteListCursorAdapter;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.ProfileImageLoader;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class BuddyTalkCursorAdapter extends CursorAdapter implements OnClickListener{

	private int mLayout;
	private LayoutInflater inflater;
	private boolean mShowcheckbox;
	
	private List<Integer> mArr_group;
	
	private ArrayList<BuddyUUIDItem> item_partispants;

	private LayoutInflater mInflater;
	public static final char HANGUL_BEGIN_UNICODE = 44032; // 가
	public static final char HANGUL_END_UNICODE = 55203; // 힣
	public static final char HANGUL_BASE_UNIT = 588;//각자음 마다 가지는 글자수
	public static final char[] INITIAL_SOUND = { 'ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ',
        'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ' };
	private char new_letter;
	private String new_name;
	private BuddyInfo info = null;

	public BuddyTalkCursorAdapter(Context context, Cursor c, int flags, List<BuddyUUIDItem> item_partispants, boolean showcheckbox, List<Integer> arr_group) {
		super(context, c, flags);
		mLayout = R.layout.list_item_buddy;
		this.mShowcheckbox = showcheckbox;
		this.item_partispants = (ArrayList<BuddyUUIDItem>) item_partispants;
		this.mArr_group = arr_group;
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		inflater = LayoutInflater.from(context);
		View v = inflater.inflate(mLayout, parent, false);
	
		ViewHolder holder = new ViewHolder();
		holder.item = (LinearLayout) v.findViewById(R.id.llayout01);
		holder.item1 = (RelativeLayout) v.findViewById(R.id.rlayoutGroup);
		holder.mGroupName = (TextView) v.findViewById(R.id.buddy_group_name);
		
		holder.item2 = (RelativeLayout) v.findViewById(R.id.rlayoutChild);
		holder.mChildCheck = (CheckBox) v.findViewById(R.id.buddy_child_check);
		holder.mProfile = (ImageView) v.findViewById(R.id.buddy_child_profile);
		holder.mBirthdayImage = (ImageView) v.findViewById(R.id.birthday_img);
		holder.mChildName = (TextView) v.findViewById(R.id.buddy_child_name);
		holder.mStatus = (TextView) v.findViewById(R.id.buddy_child_status_msg);
		holder.mRelationImage = (ImageView) v.findViewById(R.id.buddy_relation_img);
		holder.mBirthdayImage.setVisibility(View.GONE);
		
		if(!mShowcheckbox){
			holder.mChildCheck.setVisibility(View.GONE);
		} else {
			holder.mChildCheck.setVisibility(View.VISIBLE);
		}
		
		
		v.setTag(holder);
		return v;
	}
	
	private static class ViewHolder {
		LinearLayout item;
		RelativeLayout item1;
		TextView mGroupName;
		
		RelativeLayout item2;
		CheckBox mChildCheck;
		ImageView mProfile;
		ImageView mBirthdayImage;
		TextView mChildName;
		TextView mStatus;
		ImageView mRelationImage;
		
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (!mDataValid) {
            throw new IllegalStateException("this should only be called when the cursor is valid");
        }
        if (!mCursor.moveToPosition(position)) {
            throw new IllegalStateException("couldn't move cursor to position " + position);
        }

        View v;
        if (convertView == null) {
            v = newView(mContext, mCursor, parent);
        } else {
            v = convertView;
        }
        
        /** 초성을 판별하여 인덱스 생성*/
        String a = mCursor.getString(mCursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_DISPLAYNICK));
        if(a == null || "".equals(a)){
        	a = " ";
        }
        char b = a.charAt(0);
        char c;
        if(b < HANGUL_BEGIN_UNICODE){
        	c = b;
        } else{
        	c = INITIAL_SOUND[(b-HANGUL_BEGIN_UNICODE)/HANGUL_BASE_UNIT];
        }
        
        new_letter = c;
        new_name = Character.toString(new_letter);
        if(!mArr_group.contains(0) && mCursor.getPosition() == 0) new_name = mContext.getString(R.string.buddy_new_buddy);
        if(mArr_group.contains(mCursor.getPosition()) || mCursor.getPosition() == 0){
        	v.findViewById(R.id.rlayoutGroup).setVisibility(View.VISIBLE);
        } else {
        	v.findViewById(R.id.rlayoutGroup).setVisibility(View.GONE);
        }
        
        bindView(v, mContext, mCursor);
        return v;
	}
	
	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		ViewHolder holder = (ViewHolder)view.getTag();
		final long buddyUuidMsb = cursor.getLong(cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_UUID_MSB));
		final long buddyUuidLsb = cursor.getLong(cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_UUID_LSB));
		int buddyInfo = cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_INFO);
		int buddyDisplayName = cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_DISPLAYNAME);
		int buddyDisplayNick = cursor.getColumnIndexOrThrow(BuddyTable.KEY_BUDDY_DISPLAYNICK);
		BuddyUUIDItem item = new BuddyUUIDItem(buddyUuidMsb, buddyUuidLsb, cursor.getString(buddyDisplayName));
		if(!cursor.isNull(buddyDisplayNick)){
			holder.mChildName.setText(cursor.getString(buddyDisplayNick));
			try {
				info = BuddyInfo.parseFrom(cursor.getBlob(buddyInfo));
				holder.mStatus.setText(info.getProfile().getStatus());
			} catch (InvalidProtocolBufferMicroException e) {
				e.printStackTrace();
			}
			holder.mGroupName.setText(new_name);
		} else {
			holder.mChildName.setText("");
		}
		
		if(item_partispants.contains(item)){
			holder.mChildCheck.setChecked(true);
		} else {
			holder.mChildCheck.setChecked(false);
		}
		
		holder.mChildCheck.setOnClickListener(this);
		holder.mProfile.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				File file = new File(MTalkConstant.MTALK_PATH + "/buddy/" + GpbSupport.UuidMsgToString(GpbSupport.makeUuidMsg(buddyUuidMsb, buddyUuidLsb)));
				if(!file.exists() || info.getProfile().getProfileImage() == null || info.getProfile().getProfileImage().getFileName().equals("null")){
					return;
				}
				Intent intent = new Intent(mContext, ProfileImageView.class);
				intent.putExtra("msb", buddyUuidMsb);
				intent.putExtra("lsb", buddyUuidLsb);
				mContext.startActivity(intent);
			}
		});
		
		if(info.getProfile().getBirthday() != null && info.getProfile().getBirthday().getDay() != -1){
			FavoriteListCursorAdapter.birthCheck(holder.mBirthdayImage, info.getProfile().getBirthday());
		} else {
			holder.mBirthdayImage.setVisibility(View.GONE);
		}
		
		holder.mChildCheck.setTag(item);
		ProfileImageLoader.getInstance(mContext).loadProfileImage(holder.mProfile, 
				GpbSupport.UuidMsgToString(GpbSupport.makeUuidMsg(buddyUuidMsb, buddyUuidLsb)));
	}
	
	@Override
	public void changeCursor(Cursor cursor) {
		super.changeCursor(cursor);
	}
	
	@Override
	public Cursor swapCursor(Cursor newCursor) {
		return super.swapCursor(newCursor);
	}
	
	@Override
	public void onClick(View v) {
		if(v.getId() == R.id.buddy_child_check) {
			BuddyUUIDItem item = (BuddyUUIDItem) v.getTag();
			if(!item_partispants.contains(item)) {
				item_partispants.add(item);
			} else if(item_partispants.contains(item)) {
				item_partispants.remove(item);
			}
		}
	}
}
